package com.spring.security.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;


public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {
    //应用ID
    private String appId;

    //用户OpenID
    private String openId;

    private String accessToken;

    //获取用户openId的URL
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    //获取用户信息url
    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取openid
     * 响应： callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
     *
     * @param accessToken
     * @param appId
     */
    public QQImpl(String accessToken, String appId) {
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        this.accessToken = accessToken;

        // 之所以需要获取openId,是因为需要通过openId获取用户信息
        this.openId = requestOpenId(accessToken);

    }

    /**
     * 获取openId
     *
     * <p>响应： callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
     *
     * @param accessToken
     * @return
     */
    private String requestOpenId(String accessToken) {
        String url = String.format(URL_GET_OPENID, accessToken);
        String result = getRestTemplate().getForObject(url, String.class);
        System.out.println("获取openId：" + result);
        String first = StringUtils.substringBeforeLast(result, "\"");
        return StringUtils.substringAfterLast(first, "\"");
    }

    /**
     * 获取用户信息
     *
     * <p>https://wiki.connect.qq.com/get_user_info
     *
     * @return
     */
    @Override
    public QQUserInfo getUserInfo() {
        //发送请求
        String url = String.format(URL_GET_USERINFO, appId, openId);
        String result = getRestTemplate().getForObject(url, String.class);
        System.out.println("获取用户资料：" + result);

        try {
            QQUserInfo qqUserInfo = objectMapper.readValue(result, QQUserInfo.class);
            qqUserInfo.setOpenId(openId);
            return qqUserInfo;
        } catch (Exception e) {
            System.out.println(e);
            throw new RuntimeException("获取用户信息失败");
        }
    }
}
